const mongoose=require('mongoose');
const glob=require('glob');
const {resolve}=require('path');

const db="mongodb://localhost/douban-trailer"
mongoose.Promise=global.Promise;
exports.initSchemas=()=>{
    glob.sync(resolve(__dirname,'./schema','**/*.js')).forEach(require)
}
exports.connect=()=>{
    let maxConnectTimes=0;
    return new Promise((reslove,reject)=>{
        if(process.env.NODE_ENV!=="production"){
            mongoose.set('debug',true)
        }
        mongoose.connect(db,{useNewUrlParser: true})
        mongoose.connection.on('disconnected',()=>{
            maxConnectTimes++
            if(maxConnectTimes<5){
                mongoose.connect(db)
            }else{
                throw new Error("数据库挂了")
            }
        })
        mongoose.connection.on('error',(err)=>{
            reject()
           console.log(err)
        });
        mongoose.connection.once('open',()=>{
            reslove()
            console.log("连接成功")
         })
    })
    
}